package com.ebuildy.extendedcairngorm.service
{
	import com.adobe.serialization.json.JSONDecoder;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	
	import mx.managers.CursorManager;
	import mx.rpc.IResponder;
	
	public class UrlLoaderDelegate implements IServerControllerDelegate
	{
		private var responder:IResponder;
		private var loader:URLLoader;
		public var url:String;
		
		public function UrlLoaderDelegate()
		{			
			this.loader = new URLLoader();
			
			this.loader.addEventListener(IOErrorEvent.IO_ERROR, onIoError);
			this.loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecureError);
			this.loader.addEventListener(Event.COMPLETE, onComplete);
		}
		
		public function call(responder:IResponder,data:Object = null):void
		{
			this.responder = responder;
			
			var q:URLRequest = new URLRequest(this.url);
			
			q.method = URLRequestMethod.GET;
			q.data = new URLVariables();
						
			for (var p:String in data)
			{
				q.data[p] = data[p];
			}
			
			if (data.hasOwnProperty("data"))
			{
				for (p in data.data)
				{
					q.data[p] = data.data[p];
				}
			}
			
			this.loader.load(q);
			
			CursorManager.setBusyCursor();			
		}
		
		private function onComplete(e:Event):void
		{
			var dataObject:Object;
			
			try
			{
				dataObject = (new JSONDecoder(this.loader.data as String)).getValue();
			}
			catch (ex:*)
			{
				this.responder.fault("Impossible to parse data to JSON format!\n" + this.loader.data);
				this.clear();
				return ;
			}
			
			this.responder.result(dataObject);
			this.clear();
		}
		
		private function onIoError(e:IOErrorEvent):void
		{
			this.responder.fault(this.url + " not found!");
			this.clear();
		}
		
		private function onSecureError(e:SecurityError):void
		{
			this.responder.fault(this.url + " caused a security error!");
			this.clear();
		}
		
		private function clear():void
		{
			this.loader.removeEventListener(IOErrorEvent.IO_ERROR, onIoError);
			this.loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR,onSecureError);
			this.loader.removeEventListener(Event.COMPLETE, onComplete);
			
			CursorManager.removeBusyCursor();
			
			this.loader.close();
			this.loader = null;
			this.url = null;
			this.responder = null;
		}

	}
}